//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.example;

import java.util.concurrent.TimeUnit;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.redisson.Redisson;
import org.redisson.api.RSetCache;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;

public class Main {
    // 默认Redis连接设置
    private static final String DEFAULT_REDIS_HOST = "127.0.0.1";
    private static final int DEFAULT_REDIS_PORT = 6379;
    private static final String DEFAULT_REDIS_PASSWORD = null;

    public static void main(String[] args) {
        Options options = createOptions();
        CommandLineParser parser = new DefaultParser();
        HelpFormatter formatter = new HelpFormatter();

        try {
            CommandLine cmd = parser.parse(options, args);
            if (cmd.hasOption("help") || args.length == 0) {
                formatter.printHelp("RSetCache工具", options);
                return;
            }

            String setName = cmd.getOptionValue("set");
            if (setName == null || setName.trim().isEmpty()) {
                System.err.println("错误：必须指定集合名称，请使用 --set 选项");
                formatter.printHelp("RSetCache工具", options);
                return;
            }

            RedissonClient redisson = getRedissonClient(cmd);
            RSetCache<String> setCache = redisson.getSetCache(setName);

            try {
                if (cmd.hasOption("add")) {
                    String value = cmd.getOptionValue("add");
                    long ttl = Long.parseLong(cmd.getOptionValue("ttl", "0"));
                    if (ttl > 0L) {
                        setCache.add(value, ttl, TimeUnit.SECONDS);
                        System.out.println("成功添加元素: " + value + " (TTL: " + ttl + "秒)");
                    } else {
                        setCache.add(value);
                        System.out.println("成功添加元素: " + value + " (无过期时间)");
                    }
                } else if (cmd.hasOption("remove")) {
                    String value = cmd.getOptionValue("remove");
                    boolean removed = setCache.remove(value);
                    if (removed) {
                        System.out.println("成功删除元素: " + value);
                    } else {
                        System.out.println("元素不存在: " + value);
                    }
                } else if (cmd.hasOption("list")) {
                    System.out.println("集合 '" + setName + "' 中的元素:");

                    for(String value : setCache) {
                        System.out.println(" - " + value);
                    }

                    System.out.println("元素总数: " + setCache.size());
                } else if (cmd.hasOption("clear")) {
                    setCache.clear();
                    System.out.println("已清空集合 '" + setName + "'");
                } else {
                    System.err.println("错误：请指定要执行的操作（添加、删除、列表或清空）");
                    formatter.printHelp("RSetCache工具", options);
                }
            } finally {
                redisson.shutdown();
            }
        } catch (ParseException e) {
            System.err.println("解析命令行参数时出错: " + e.getMessage());
            formatter.printHelp("RSetCache工具", options);
        } catch (Exception e) {
            System.err.println("操作过程中出错: " + e.getMessage());
            e.printStackTrace();
        }

    }

    private static Options createOptions() {
        Options options = new Options();
        options.addOption(Option.builder("h").longOpt("help").desc("显示帮助信息").build());
        options.addOption(Option.builder("s").longOpt("set").desc("要操作的集合名称").hasArg().argName("SET_NAME").build());
        options.addOption(Option.builder("a").longOpt("add").desc("添加元素到集合").hasArg().argName("VALUE").build());
        options.addOption(Option.builder("t").longOpt("ttl").desc("元素的生存时间(秒)").hasArg().argName("SECONDS").build());
        options.addOption(Option.builder("r").longOpt("remove").desc("从集合中删除元素").hasArg().argName("VALUE").build());
        options.addOption(Option.builder("l").longOpt("list").desc("列出集合中所有元素").build());
        options.addOption(Option.builder("c").longOpt("clear").desc("清空集合中的所有元素").build());

        // Redis连接选项
        options.addOption(Option.builder().longOpt("host").desc("Redis服务器主机名或IP地址").hasArg().argName("HOST").build());
        options.addOption(Option.builder().longOpt("port").desc("Redis服务器端口").hasArg().argName("PORT").type(Number.class).build());
        options.addOption(Option.builder().longOpt("password").desc("Redis服务器密码").hasArg().argName("PASSWORD").build());

        return options;
    }

    private static RedissonClient getRedissonClient(CommandLine cmd) {
        Config config = new Config();

        // 获取命令行参数中的Redis连接设置
        String host = cmd.getOptionValue("host", DEFAULT_REDIS_HOST);
        int port = Integer.parseInt(cmd.getOptionValue("port", String.valueOf(DEFAULT_REDIS_PORT)));
        String password = cmd.getOptionValue("password", DEFAULT_REDIS_PASSWORD);

        ((SingleServerConfig)config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password)).setConnectionMinimumIdleSize(1).setConnectionPoolSize(2);
        return Redisson.create(config);
    }
}
